<?php


namespace App\Model;
use EasySwoole\ORM\AbstractModel;
use EasySwoole\ORM\Exception\Exception;
use EasySwoole\ORM\Utility\Schema\Table;

//重写/覆盖一些ES自带的ORM弊端
class BaseModel extends AbstractModel{

    /** 包装查询不到的情况下返回 0
     * @param $field
     * @return int|mixed|null
     * @throws Exception
     * @throws \Throwable
     * *    author 韩天尊
     */
    public function sum($field)
    {
        $data = parent::sum($field); //TODO: Change the autogenerated stub
        if ($data == null){
            $data = 0; }
        return $data;
    }

    /** 兼容自定义的获取器append多对象调用
     * @param $selfArray
     * @param $append
     * @return mixed
     * *    author 韩天尊
     * 常规的自定义append仅支持 $this->get()->appent(["xxx"]);
     * 用法：$this->allAppend($this->all(), ["xxx"]);
     */
    public function allAppend($selfArray, $append)
    {
        foreach ($selfArray as &$smthis){
            $smthis->append = $smthis->append($append);
        }
        return $selfArray;
    }

    /**
     * @param array $where
     * @param bool $order
     * @param int $page
     * @param int $pageSize
     * @param string $field
     * @return array
     * @throws Exception
     * @throws \Throwable
     */
    public function recvData(array $where=[], bool $order=true, int $page = 1, int $pageSize = 15, string $field = '*'): array
    {
        $list = $this
            ->withTotalCount()
            ->order($this->schemaInfo()->getPkFiledName(), $order?"ASC":"DESC")
            ->field($field)
            ->page($page, $pageSize)
            ->all($where);
        $total = $this->lastQueryResult()->getTotalCount();
        $data = [
            'page'=>$page,
            'pageSize'=>$pageSize,
            'list'=>$list,
            'total'=>$total,
            'pageCount'=>ceil($total / $pageSize)
        ];
        return $data;
    }


    /** 分页 where 处理 (如果出现like  >= <= 需要重新构造处理)
     * @param array $rawWhere url ?后的那一串
     * @param string $whereOrder 返回的where顺序 "id,name,xxx"
     * @throws Exception *    author 韩天尊
     */
    public function paginationFilterWhere(array $rawWhere, string $whereOrder=""):array
    {
        $columns = $this->schemaInfo()->getColumns();//获取表字段结构
        $whereOrderArray = empty($whereOrder)? [] : explode(",", $whereOrder);
        $whereKeys = array_keys($rawWhere);
        $where = [];
        foreach ($whereKeys as $where_key){
            if (isset($rawWhere[$where_key]) && isset($columns[$where_key])){
                $where[$where_key] = $rawWhere[$where_key];
            }
        }
        $filterWhere = [];
        if (empty($whereOrderArray)){
            $filterWhere = $where;
        }
        $orderKeys = array_keys($whereOrderArray);//指定where顺序
        foreach ($orderKeys as $order_key){
            if (isset($where[$order_key])){
                $filterWhere[$order_key] = $where[$order_key];
            }
        }
        return $filterWhere;
    }
}